//
//  ChartView.swift
//  PBFinanceBusiness
//
//  Created by xinph on 2020/7/23.
//

import UIKit
import CZBFoundation
import PBGlobalization

let notFoundHighlight = -1
let margin: CGFloat = 4

// MARK: - life cycle
open class ChartView: CZBView {
    
    open var scales: [String] = []
    open var periods: [Int] = []
    open var displayHighlightIndex = notFoundHighlight
    /// 所有柱子(或者除了一个显示其他颜色)都显示灰色
    open var allOrExceptOneShownGrayColor: Bool = false
    
    lazy var incomeLabel: UILabel = {
        var lazyView = UILabel(font: .size(12), textColor: UIColor.hex("#9b9bab"))
        lazyView.text = LocalizableKeys.financial(.incomeRate).value
        return lazyView
    }()
    
    /// x轴
    lazy var axisX: UIView = {
        var lazyView = UIView()
        lazyView.backgroundColor = UIColor.hex("#D8D8E0")
        return lazyView
    }()
    
    lazy var lineH: UIView = {
        var lazyView = UIView()
        lazyView.backgroundColor = UIColor.hex("#D8D8E0")
        return lazyView
    }()
    
    /// y轴
    lazy var axisY: UIView = {
        var lazyView = UIView()
        lazyView.backgroundColor = UIColor.hex("#D8D8E0")
        return lazyView
    }()
    
    lazy var lineV: UIView = {
        var lazyView = UIView()
        lazyView.backgroundColor = UIColor.hex("#D8D8E0")
        return lazyView
    }()
}

extension ChartView {
    public func updateLayout() {
        self.subviews.forEach { $0.removeFromSuperview() }
        
        addSubview(incomeLabel)
        incomeLabel.snp.makeConstraints { (make) in
            make.left.top.equalTo(RealValue(20))
        }
        /// 创建坐标系
        drawCoordinateSystem()
        /// 创建渐变条
        createGradientBars()
    }
}

// MARK: - UI
extension ChartView {
    open override func setupUI() {
        backgroundColor = .white
        addSubview(incomeLabel)
        incomeLabel.snp.makeConstraints { (make) in
            make.left.top.equalTo(RealValue(20))
        }
        /// 创建坐标系
        drawCoordinateSystem()
        /// 创建渐变条
        createGradientBars()
    }
    
    /// 绘制坐标系
    fileprivate func drawCoordinateSystem() {
        addSubview(lineH)
        addSubview(lineV)
        addSubview(axisX)
        addSubview(axisY)
                
        lineH.snp.makeConstraints { (make) in
            make.left.equalTo(RealValue(20))
            make.top.equalTo(incomeLabel.snp.bottom).offset(RealValue(8))
            make.height.equalTo(1)
            make.width.equalTo(RealValue(12))
        }
        
        axisY.snp.makeConstraints { (make) in
            make.top.equalTo(lineH.snp.bottom)
            make.centerX.equalTo(lineH.snp.centerX)
            make.bottom.equalTo(axisX.snp.top)
            make.width.equalTo(1)
        }
        
        axisX.snp.makeConstraints { (make) in
            make.left.equalTo(axisY.snp.left)
            make.height.equalTo(1)
            make.right.equalTo(lineV.snp.left)
            make.bottom.equalTo(RealValue(-40))
        }
        
        lineV.snp.makeConstraints { (make) in
            make.centerY.equalTo(axisX.snp.centerY)
            make.width.equalTo(1)
            make.height.equalTo(lineH.snp.width)
            make.right.equalTo(RealValue(-20))
        }
    }
    
    fileprivate func createGradientBars() {
        /// n > 1
        var bars: [GradientChartBar] = []
        
        let values = caluteScales(scales)
        guard values.count == scales.count else { return }
                
        for i in 0..<scales.count {
            var bar: GradientChartBar
            /// 所有柱子(或者除了一个显示其他颜色)都显示灰色
            if allOrExceptOneShownGrayColor {
                /// 当前索引不存在,都显示灰色
                if displayHighlightIndex == notFoundHighlight || displayHighlightIndex >= scales.count{
                    bar = GradientChartBar(false, scale: values[i], colors: [UIColor.hex("#D8D8E0")], title: scales[i])
                    bar.titleLabel.textColor = UIColor.hex("#9B9BAB")
                    bar.gradientView.alpha = 1-0.05*CGFloat((scales.count-i+1))
                } else {
                    if displayHighlightIndex == i {
                        bar = GradientChartBar(scale: values[i], title: scales[i])
                    } else {
                        bar = GradientChartBar(false, scale: values[i], colors: [UIColor.hex("#D8D8E0")], title: scales[i])
                        bar.titleLabel.textColor = UIColor.hex("#9B9BAB")
                        bar.gradientView.alpha = 1-0.05*CGFloat((scales.count-i+1))
                    }
                }
            } else {
                bar = GradientChartBar(scale: values[i], title: scales[i])
                bar.gradientView.alpha = 1-0.05*CGFloat((scales.count-i+1))
            }
            
            addSubview(bar)
            updateBarsLayout(bars.last, current: bar, isLast: i==scales.count-1)
            bars.append(bar)
        }
        
        /// 创建x轴时间周期
        createPeriodLabels(periods, bars: bars)
    }
    
    /// 更新bar布局
    /// n > 1
    fileprivate func updateBarsLayout(_ pre: GradientChartBar?, current: GradientChartBar, isLast: Bool) {
        guard let pre = pre else {
             current.snp.makeConstraints { (make) in
                make.top.equalTo(axisY.snp.top)
                make.left.equalTo(axisY.snp.right)
                make.bottom.equalTo(axisX.snp.top)
             }
            return
        }
        
        current.snp.makeConstraints { (make) in
            make.top.equalTo(axisY.snp.top)
            make.left.equalTo(pre.snp.right).offset(margin)
            make.width.equalTo(pre.snp.width)
            make.bottom.equalTo(axisX.snp.top)
            if isLast {
                make.right.equalTo(lineV.snp.left)
            }
        }
    }
    
    
    /// 创建横坐标时间周期
    /// - Parameter periods: 时间周期
    fileprivate func createPeriodLabels(_ periods: [Int], bars: [GradientChartBar]) {
        guard periods.count == bars.count else { return }
        
        for (index, days) in periods.enumerated() {
            let label = UILabel(font: .systemFont(ofSize: 12), textColor: UIColor.hex("#9b9bab"))
            label.text = "\(days)天"
            addSubview(label)

            let bar = bars[index]
            label.snp.makeConstraints { (make) in
                make.top.equalTo(axisX.snp.bottom).offset(RealValue(8))
                if index == 0 {
                    make.left.equalTo(axisY.snp.right)
                } else {
                    make.centerX.equalTo(bar.snp.left).offset(-margin/2)
                }
            }
        }
    }

    fileprivate func caluteScales(_ scales: [String]) -> [String] {
        var dst: [String] = []
        var max: String = "0"
        for val in scales {
            if CompareNumber(with: max, otherNumber: val) == .orderedAscending {
                max = val
            }
        }
        guard max > "0" else { return [] }
        for val in scales {
            dst.append(Dividing(val, otherNumber: max)!)
        }
        return dst
    }
}

// MARK: - Action
extension ChartView {
    
}

// MARK: - Delegate
extension ChartView {
    
}
